// @algorithm @lc id=1000239 lang=typescript
// @title 1fGaJU
// @test([0,0,0])=[[0,0,0]]
function threeSum(nums: number[]): number[][] {
  nums.sort((a, b) => a - b);
  const n = nums.length;
  const ans = [];
  for (let i = 0; i < n && nums[i] <= 0; i++) {
    // 去重
    if (i > 0 && nums[i] === nums[i - 1]) continue;
    const target = 0 - nums[i];
    let l = i + 1;
    let r = n - 1;
    while (l < r) {
      if (nums[l] + nums[r] === target) {
        ans.push([nums[i], nums[l], nums[r]]);
        // 去重
        while (l < r && nums[l] === nums[l + 1]) {
          l++;
        }
        l++;
      } else if (nums[l] + nums[r] > target) {
        r--;
      } else {
        l++;
      }
    }
  }
  return ans;
}
